/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.action;

import com.jspx.boot.environment.Environment;
import com.jspx.boot.sign.LanguageRes;
import com.jspx.json.JSONArray;
import com.jspx.json.JSONObject;
import com.jspx.security.utils.EncryptUtil;
import com.jspx.txweb.IUserSession;
import com.jspx.txweb.annotation.HttpMethod;
import com.jspx.txweb.annotation.Operate;
import com.jspx.txweb.env.TXWeb;
import com.jspx.txweb.util.TXWebUtil;
import com.jspx.utils.*;
import javax.jws.WebMethod;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: yuan
 * Date: 12-12-15
 * Time: 上午10:43
 * 远程登陆接口
 *
 */
@HttpMethod(caption = "认证登陆接口")
public class AuthenticationAction extends BaseUserAction {

    public AuthenticationAction()
    {
        setActionResult(NONE);
    }

    @WebMethod(exclude = false)
    @Operate(caption = "公密")
    public void publicKey() throws Exception {
        String publicKeyHost = StringUtil.trim(config.getString(Environment.publicKeyHost));
        if (!IpUtil.interiorly(publicKeyHost,getRemoteAddr()))
        {
            TXWebUtil.print(language.getLang(LanguageRes.notAllowedIpLimits), TXWebUtil.htmlType, response);
            return;
        }
        int publicKeyHour = config.getInt(Environment.publicKeyHour,1);
        if  (publicKeyHour<=0)
        {
            publicKeyHour = 2;
            config.save(Environment.publicKeyHour,publicKeyHour + StringUtil.empty);
        }
        if (StringUtil.isNULL(TXWeb.publicKey) || System.currentTimeMillis()- TXWeb.publicKeyCreateTimeMillis>DateUtil.HOUR*publicKeyHour)
        {
            TXWeb.publicKey = EncryptUtil.getMd5(System.currentTimeMillis() + RandomUtil.getRandomNumeric(32));
            TXWeb.publicKeyCreateTimeMillis = System.currentTimeMillis();
            config.flush();
        }
        TXWebUtil.print(TXWeb.publicKey, TXWebUtil.htmlType, response);
    }

    @Operate(caption = "判断在线",submit = false)
    public void checkSession() throws Exception {
        String sessionId = getString(TXWeb.sessionId);
        if (StringUtil.isNULL(sessionId))
        {
            TXWebUtil.print("0", TXWebUtil.htmlType, response);
            return;
        }
        IUserSession userSession  = onlineManager.getUserSession(sessionId);
        if (userSession!=null&&!userSession.isGuest())
        {
            TXWebUtil.print("1", TXWebUtil.htmlType, response);
        } else
            TXWebUtil.print("0", TXWebUtil.htmlType, response);
    }

    @Override
    @Operate(caption="退出",submit = false)
    public void exit() throws Exception
    {
        String sessionId = getString(TXWeb.sessionId);
        if (StringUtil.isNULL(sessionId))
        {
            TXWebUtil.print("0", TXWebUtil.htmlType, response);
            return;
        }
        onlineManager.exit(this);
        TXWebUtil.print("1", TXWebUtil.htmlType, response);
    }

    @Override
    @Operate(caption = "远程登录接口")
    public void login() throws Exception {
        setActionResult(ROC);
        if (!config.getBoolean(Environment.userRemoteLogin))
        {
            addFieldInfo(Environment.warningInfo,language.getLang(LanguageRes.interfaceClosed));
            return;
        }

        //此验证码为参数校验
        String verify = getString("verify",true);
        if (StringUtil.isNULL(verify)) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.notInputValidate));
            return;
        }

        setPublicKey(TXWeb.publicKey);
        setPrivateKey(StringUtil.trim(config.get(Environment.privateKey)));


        long verifySecond = System.currentTimeMillis() - timeMillis;
        if (Math.abs(verifySecond) >DateUtil.MINUTE*5){
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.authenticationTimeOut)+"," + verifySecond);
            return;
        }

        //getMakeVerify 必须先设置参数
        if (!verify.equals(getMakeVerify()))
        {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.validationFailure));
            return;
        }

        //判断IP范围
        String ip = getRemoteAddr();
        if (!IpUtil.interiorly(config.get(Environment.authIpExpression),ip))
        {
            addFieldInfo(Environment.warningInfo,language.getLang(LanguageRes.notAllowedIpLimits));
            return;
        }

        int loginTimes = ObjectUtil.toInt(session.getAttribute(Environment.id_loginTimes));
        if (loginTimes>config.getInt(Environment.maxLoginTimes)) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.validationFailureLimitTimes) + loginTimes);
            return;
        }

        Map<String, String> loginInfo =  onlineManager.login(this, field,loginId,password, passwordEncoded, getInt("cookieSecond",0), 0);
        if (!loginInfo.isEmpty()) {
            addFieldInfo(loginInfo);
            //添加错误信息
        }

        boolean isLogin = loginInfo.isEmpty();

        int mode = getMode();
        IUserSession userSession = onlineManager.getUserSession(this);


        if (isLogin)
        {
            session.removeAttribute(Environment.id_loginTimes);
            JSONObject json = new JSONObject();
            json.put(Environment.id_success, 1);
            json.put(Environment.id_loginTimes, loginTimes);
            json.put(TXWeb.sessionId, userSession.getSid());
            json.put(Environment.infoType,Environment.promptInfo);
            json.put(Environment.message,language.getLang(LanguageRes.loginSuccess));
            if (hasFieldInfo())
            {
                JSONArray jsonArray = new JSONArray();
                for (String info : getFieldInfo().values()) {
                    jsonArray.put(info);
                }
                json.put(Environment.id_message_list,jsonArray);
            }
            setResult(json);
            setActionResult(ROC);
        } else {
            loginTimes++;
            if (mode == 0)
            {
                addActionMessage(language.getLang(LanguageRes.loginFailure));
            } else {
                JSONObject json = new JSONObject();
                json.put(Environment.id_success,0);
                json.put(Environment.id_loginTimes, loginTimes);
                json.put(TXWeb.sessionId, userSession.getSid());
                json.put(Environment.infoType,Environment.warningInfo);
                json.put(Environment.id_message,language.getLang(LanguageRes.loginFailure));
                JSONArray jsonArray = new JSONArray();
                for (String info : getFieldInfo().values()) {
                    jsonArray.put(info);
                }
                json.put(Environment.id_message_list,jsonArray);
                setResult(json);
            }
        }
        if (session != null) {
            put(Environment.id_loginTimes, loginTimes);
        }
    }

}